﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using ESoft.DataAccess.Models;

namespace ESoft.DataAccess.EfCore
{
    /// <summary>
    /// 数据库初始化操作类
    /// </summary>
    public class DatabaseInitializer
    {
        private static readonly ICollection<Assembly> MapperAssemblies = new List<Assembly>();

        /// <summary>
        /// 获取 数据实体映射配置信息集合
        /// </summary>
        public static ICollection<EntityBase> EntityMappers
        {
            get { return GetAllEntityMapper(); }
        }

        /// <summary>
        /// 设置数据库初始化，策略为自动迁移到最新版本
        /// </summary>
        public static void Initialize()
        {
        }

        /// <summary>
        /// 添加需要搜索实体映射的程序集到检索集合中
        /// </summary>
        public static void AddMapperAssembly(params Assembly[] assemblys)
        {
            foreach (var assembly in assemblys)
            {
                if (MapperAssemblies.Any(m => m == assembly))
                {
                    return;
                }

                MapperAssemblies.Add(assembly);
            }
        }

        private static ICollection<EntityBase> GetAllEntityMapper()
        {
            Type baseType = typeof(EntityBase);
            Type[] mapperTypes = MapperAssemblies.SelectMany(assembly => assembly.GetTypes())
                .Where(type => baseType.IsAssignableFrom(type) && type != baseType && !type.IsAbstract).ToArray();
            ICollection<EntityBase> result = mapperTypes.Select(type => Activator.CreateInstance(type) as EntityBase).ToList();
            return result;
        }
    }
}
